<?php
/**
 *
 * Author: Lyu
 * Date: 2023/7/25
 * Time: 15:53
 */

namespace App\Service\Core\Admin\Role;

use App\Model\Core\Admin\AdminUserModel;
use App\Model\Core\Admin\AdminUserPowerModel;
use App\Model\Core\Admin\AdminUserRoleModel;
use App\Service\Core\CoreBaseService;
use App\Traits\SingleInstanceTrait;
use function Psr\Log\alert;

class AdminUserRoleService extends CoreBaseService
{
    use SingleInstanceTrait;

    public function getOne($role_id, $is_cache = true): array
    {
        $role_id = (int)$role_id;
        return AdminUserRoleModel::getInstance()->getOne($role_id, $is_cache);
    }

    public function getRoleSelect($is_cache = true): array
    {
        $select = [];
        $role_list = AdminUserRoleModel::getInstance()->getUsableRoleList($is_cache);
        foreach ($role_list as $item) {
            $select[] = ['id' => $item['role_id'], 'label' => $item['name']];
        }
        return $select;
    }

    public function changeStatus($role_id, $status, $operate_id, $operate_by): array
    {
        $role_info = AdminUserRoleModel::getInstance()->getOne((int)$role_id);
        if (empty($role_info)) {
            return alert_info(1, '角色不存在');
        }
        if ($status == $role_info['status']) {
            return alert_info(0, '状态无需修改');
        }
        $res = AdminUserRoleModel::getInstance()->updateOne($role_id, ['status' => $status, 'updated_by' => $operate_by, 'updated_at' => date('Y-m-d H:i:s')]);
        if ($res === false) {
            return alert_info(1, '操作失败:数据库繁忙');
        }
        $this->addLog('角色管理', '修改角色【' . $role_id . '】状态【' . $status . '】', $operate_id, $operate_by);
        return alert_info(0, '操作成功');
    }

    public function deleteRole($role_id, $operate_id, $operate_by)
    {
        $role_id = trim($role_id);
        if (!is_numeric($role_id) || $role_id <= 0) return alert_info(1, '角色ID不能为空');
        $role_info = AdminUserRoleModel::getInstance()->getOne((int)$role_id);
        if (empty($role_info)) return alert_info(1, '角色不存在');
        $check = obj_to_array(AdminUserModel::getInstance()->getConnectionTable()->whereRaw("find_in_set($role_id,role_id)")->first());
        if (!empty($check)) return alert_info(1, "员工【{$check['username']}】正在使用该角色，请先删除");
        //删除角色权限
        $conn = AdminUserRoleModel::getInstance()->getConnection();
        $conn->beginTransaction();
        $res = AdminUserPowerModel::getInstance()->deleteRole($role_id);
        if ($res === false) {
            $conn->rollBack();
            return alert_info(1, '角色权限删除失败');
        }
        //删除角色
        $res = AdminUserRoleModel::getInstance()->deleteOne($role_id);
        if ($res === false) {
            $conn->rollBack();
            return alert_info(1, '角色删除失败');
        }
        $conn->commit();
        $this->addLog('角色管理', '删除角色【' . $role_info['name'] . '】ID【' . $role_id . '】', $operate_id, $operate_by);
        return alert_info(0, '操作成功');
    }
}
